// 数据存储管理工具
// 使用 uni-app 的本地存储API

const STORAGE_KEYS = {
  RECORDS: 'accounting_records',
  CATEGORIES: 'accounting_categories',
  SETTINGS: 'accounting_settings',
  USER_INFO: 'accounting_user_info'
}

/**
 * 保存记账记录
 * @param {Array} records 记录数组
 */
export const saveRecords = (records) => {
  try {
    uni.setStorageSync(STORAGE_KEYS.RECORDS, records)
    return true
  } catch (e) {
    console.error('保存记录失败:', e)
    return false
  }
}

/**
 * 获取记账记录
 * @returns {Array} 记录数组
 */
export const getRecords = () => {
  try {
    const records = uni.getStorageSync(STORAGE_KEYS.RECORDS)
    return records || []
  } catch (e) {
    console.error('获取记录失败:', e)
    return []
  }
}

/**
 * 添加新记录
 * @param {Object} record 新记录对象
 * @returns {boolean} 是否成功
 */
export const addRecord = (record) => {
  try {
    const records = getRecords()
    records.unshift(record) // 添加到开头
    return saveRecords(records)
  } catch (e) {
    console.error('添加记录失败:', e)
    return false
  }
}

/**
 * 更新记录
 * @param {number} id 记录ID
 * @param {Object} updatedRecord 更新的记录
 * @returns {boolean} 是否成功
 */
export const updateRecord = (id, updatedRecord) => {
  try {
    const records = getRecords()
    const index = records.findIndex(record => record.id === id)
    if (index !== -1) {
      records[index] = { ...records[index], ...updatedRecord }
      return saveRecords(records)
    }
    return false
  } catch (e) {
    console.error('更新记录失败:', e)
    return false
  }
}

/**
 * 删除记录
 * @param {number} id 记录ID
 * @returns {boolean} 是否成功
 */
export const deleteRecord = (id) => {
  try {
    const records = getRecords()
    const filteredRecords = records.filter(record => record.id !== id)
    return saveRecords(filteredRecords)
  } catch (e) {
    console.error('删除记录失败:', e)
    return false
  }
}

/**
 * 获取指定时间范围的记录
 * @param {string} startDate 开始日期 (YYYY-MM-DD)
 * @param {string} endDate 结束日期 (YYYY-MM-DD)
 * @returns {Array} 过滤后的记录数组
 */
export const getRecordsByDateRange = (startDate, endDate) => {
  try {
    const records = getRecords()
    const start = new Date(startDate).getTime()
    const end = new Date(endDate).getTime()
    
    return records.filter(record => {
      const recordDate = new Date(record.date).getTime()
      return recordDate >= start && recordDate <= end
    })
  } catch (e) {
    console.error('按日期范围获取记录失败:', e)
    return []
  }
}

/**
 * 获取指定月份的记录
 * @param {number} year 年份
 * @param {number} month 月份 (1-12)
 * @returns {Array} 过滤后的记录数组
 */
export const getRecordsByMonth = (year, month) => {
  try {
    const records = getRecords()
    const startDate = `${year}-${String(month).padStart(2, '0')}-01`
    const lastDay = new Date(year, month, 0).getDate()
    const endDate = `${year}-${String(month).padStart(2, '0')}-${lastDay}`
    
    return getRecordsByDateRange(startDate, endDate)
  } catch (e) {
    console.error('按月份获取记录失败:', e)
    return []
  }
}

/**
 * 计算统计数据
 * @param {Array} records 记录数组
 * @returns {Object} 统计数据
 */
export const calculateStats = (records) => {
  try {
    const stats = {
      totalIncome: 0,
      totalExpense: 0,
      totalBalance: 0,
      categoryStats: {}
    }
    
    records.forEach(record => {
      if (record.type === 'income') {
        stats.totalIncome += record.amount
      } else {
        stats.totalExpense += record.amount
      }
      
      // 分类统计
      const key = `${record.type}_${record.category}`
      if (!stats.categoryStats[key]) {
        stats.categoryStats[key] = {
          name: record.category,
          type: record.type,
          amount: 0,
          count: 0
        }
      }
      stats.categoryStats[key].amount += record.amount
      stats.categoryStats[key].count += 1
    })
    
    stats.totalBalance = stats.totalIncome - stats.totalExpense
    
    return stats
  } catch (e) {
    console.error('计算统计数据失败:', e)
    return {
      totalIncome: 0,
      totalExpense: 0,
      totalBalance: 0,
      categoryStats: {}
    }
  }
}

/**
 * 保存分类配置
 * @param {Object} categories 分类配置对象
 * @returns {boolean} 是否成功
 */
export const saveCategories = (categories) => {
  try {
    uni.setStorageSync(STORAGE_KEYS.CATEGORIES, categories)
    return true
  } catch (e) {
    console.error('保存分类配置失败:', e)
    return false
  }
}

/**
 * 获取分类配置
 * @returns {Object} 分类配置对象
 */
export const getCategories = () => {
  try {
    const categories = uni.getStorageSync(STORAGE_KEYS.CATEGORIES)
    return categories || {
      expense: [
        { name: '餐饮', icon: '🍽️' },
        { name: '交通', icon: '🚇' },
        { name: '购物', icon: '🛍️' },
        { name: '娱乐', icon: '🎮' },
        { name: '医疗', icon: '🏥' },
        { name: '教育', icon: '📚' },
        { name: '住房', icon: '🏠' },
        { name: '其他', icon: '📝' }
      ],
      income: [
        { name: '工资', icon: '💰' },
        { name: '奖金', icon: '🎁' },
        { name: '投资', icon: '📈' },
        { name: '兼职', icon: '💼' },
        { name: '红包', icon: '🧧' },
        { name: '其他', icon: '📝' }
      ]
    }
  } catch (e) {
    console.error('获取分类配置失败:', e)
    return {}
  }
}

/**
 * 保存用户设置
 * @param {Object} settings 设置对象
 * @returns {boolean} 是否成功
 */
export const saveSettings = (settings) => {
  try {
    uni.setStorageSync(STORAGE_KEYS.SETTINGS, settings)
    return true
  } catch (e) {
    console.error('保存设置失败:', e)
    return false
  }
}

/**
 * 获取用户设置
 * @returns {Object} 设置对象
 */
export const getSettings = () => {
  try {
    const settings = uni.getStorageSync(STORAGE_KEYS.SETTINGS)
    return settings || {
      currency: 'CNY',
      theme: 'light',
      notifications: true,
      autoBackup: false
    }
  } catch (e) {
    console.error('获取设置失败:', e)
    return {}
  }
}

/**
 * 清除所有数据
 * @returns {boolean} 是否成功
 */
export const clearAllData = () => {
  try {
    Object.values(STORAGE_KEYS).forEach(key => {
      uni.removeStorageSync(key)
    })
    return true
  } catch (e) {
    console.error('清除数据失败:', e)
    return false
  }
}

/**
 * 导出数据
 * @returns {Object} 导出的数据对象
 */
export const exportData = () => {
  try {
    return {
      records: getRecords(),
      categories: getCategories(),
      settings: getSettings(),
      exportTime: new Date().toISOString()
    }
  } catch (e) {
    console.error('导出数据失败:', e)
    return null
  }
}

/**
 * 导入数据
 * @param {Object} data 要导入的数据对象
 * @returns {boolean} 是否成功
 */
export const importData = (data) => {
  try {
    if (data.records) {
      saveRecords(data.records)
    }
    if (data.categories) {
      saveCategories(data.categories)
    }
    if (data.settings) {
      saveSettings(data.settings)
    }
    return true
  } catch (e) {
    console.error('导入数据失败:', e)
    return false
  }
}
